package com.example.testb64;

/*
 *
 * Sample project to encode image and send it over network.
 * 
 * */

import java.io.ByteArrayOutputStream;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener
{

	//Button to execute the encoding and send the file in a B64 format over network.
	Button btnConvert;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btnConvert = (Button) findViewById(R.id.buttonConvert);
		btnConvert.setOnClickListener(this);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View v)
	{
		if (v == btnConvert)
		{
			try
			{
				encodImage();
				
				Toast.makeText(getApplicationContext(), "Encode success!",
						Toast.LENGTH_LONG).show();

			} catch (Exception e)
			{
				Toast.makeText(getApplicationContext(),
						"Exception: " + e.getMessage(), Toast.LENGTH_LONG)
						.show();
			}

		}

	}

	/**
	 * Function that load a image form resource folder and use B64 for to encode
	 * and get the string with this encoded information.
	 */
	private void encodImage()
	{
		Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),

		R.drawable.engine_icon);

		ByteArrayOutputStream bao = new ByteArrayOutputStream();

		bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

		byte[] ba = bao.toByteArray();

		String ba1 = Base64.encodeBytes(ba);
	}
}
